﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using System.Net;

namespace DreamShieldPublishRetriever
{
    public partial class MainForm : Form
    {
        public virtual ProductXml Product { get; protected set; }

        const string windows_register = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";

        public virtual Version GetInstalledVersion()
        {
            using (RegistryKey windows_uninstall = Registry.LocalMachine.OpenSubKey(windows_register, false))
            {
                RegistryKey product_key = windows_uninstall.OpenSubKey("DreamShield_" + Product.Guid.ToString(), false);
                if (product_key == null)
                {
                    /* pas installé */
                    return new Version(0, 0, 0, 0);
                }
                else
                {
                    using (product_key)
                    {
                        try
                        {
                            return new Version((string)product_key.GetValue("Version", "0.0.0.0"));
                        }
                        catch
                        {
                            return new Version(0, 0, 0, 0);
                        }
                    }
                }
            }
        }

        public virtual Version InstalledVersion { get; set; }
        public virtual Version OnlineVersion { get; set; }
        public virtual string DownloadPath { get; set; }

        public MainForm(ProductXml xml_obj)
        {
            Product = xml_obj;

            InitializeComponent();

            if (!String.IsNullOrEmpty(Product.UI.ProductImage) &&
                File.Exists(Product.UI.ProductImage))
            {
                if (!Path.IsPathRooted(Product.UI.ProductImage))
                    Product.UI.ProductImage = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar +
                        Product.UI.ProductImage;

                imageBox.Image = Image.FromFile(Product.UI.ProductImage);
            }

            titleLabel.Text = Product.UI.ProductName;
            var valid_link = !String.IsNullOrEmpty(Product.UI.ProductUrl);
            linkLabel.Visible = valid_link;
            if (valid_link)
            {
                linkLabel.Text = Product.UI.ProductUrl;
                linkLabel.Links.Add(0, Product.UI.ProductUrl.Length);
            }

            InstalledVersion = GetInstalledVersion();

            lb_actualVersion.Text = InstalledVersion.ToString();
            
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            
        }

        private void op_timer_Tick(object sender, EventArgs e)
        {
            op_timer.Enabled = false;

            if (Program.DebugRun)
            {
                ExecuteVersionsLoad();
            }
            else
            {
                try
                {
                    ExecuteVersionsLoad();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format("Une erreur non gérée s'est produite dans le programme :\n{0}", ex),
                            "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Close();
                }
            }
        }

        private void ExecuteVersionsLoad()
        {
            /* On télécharge les infos */
            using (WebClient download_client = new WebClient())
            {
                download_client.Credentials = new NetworkCredential();
                string temp_file = Path.GetTempFileName();
                try
                {
                    download_client.DownloadFile(Product.ServerXml, temp_file);
                    using (FileStream fs = new FileStream(temp_file, FileMode.Open, FileAccess.Read))
                    {
                        var online_infos = (OnlineProductSubset)OnlineProductSubset.GetSerializer().Deserialize(fs);

                        if (online_infos.ApplicationGuid != Product.Guid)
                        {
                            throw new InvalidOperationException(String.Format("Le guid de l'application décrite sur le serveur à l'addresse {0} ne correspond pas avec le guid actuel",
                                Product.ServerXml));
                        }
                        else
                        {
                            online_infos.Versions.Sort();
                            if (online_infos.Versions.Count < 1)
                            {
                                MessageBox.Show(String.Format("Aucune version de l'application {0} n'est disponible", Product.UI.ProductName),
                                    "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                Close();
                            }
                            else
                            {
                                int index = -1;
                                for (int i = online_infos.Versions.Count - 1; i >= 0; i--)
                                {
                                    if (online_infos.Versions[i].CurrentVersionDownloadAvailable)
                                    {
                                        index = i;
                                        break;
                                    }
                                }

                                if (index == -1)
                                {
                                    MessageBox.Show("Aucune des versions existantes ne sont disponibles en téléchargement",
                                        "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    Close();
                                }
                                else
                                {
                                    OnlineVersion = online_infos.Versions[index].CurrentApplicationVersion.StandardVersion;
                                    lb_availableVersion.Text = OnlineVersion.ToString();
                                    DownloadPath = online_infos.Versions[index].CurrentVersionDownloadInfo.ItemDownloadUrl;

                                    BtnExecuteDownload.Enabled = OnlineVersion.CompareTo(InstalledVersion) > 0;
                                }
                            }
                        }
                    }
                }
                finally
                {
                    File.Delete(temp_file);
                }
            }
        }

        private void BtnExecuteDownload_Click(object sender, EventArgs e)
        {
            FormDownloading downloading = new FormDownloading();
            downloading.Icon = Icon;
            Hide();
            downloading.Show();
            downloading.StartDownload(Product, DownloadPath);
            Close();
        }
    }
}
